package com.seckill.orders.listener;

import com.alibaba.fastjson.JSONObject;
import com.seckill.commons.Constants;
import com.seckill.orders.model.Orders;
import com.seckill.orders.service.OrderService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class SecKillListener {
    @Resource
    private OrderService orderService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @RabbitListener(queues = {"secKillQueue"})
    public void secKillMessageListener(String message){
        Orders orders= JSONObject.parseObject(message,Orders.class);
        //数据库下单，返回下单结果0表示下单成功
        int result=orderService.addOrder(orders);
        //进入if表示完成了数据库的下单需要将订单备份数据从Redis中删除
        if(result==0){
            stringRedisTemplate.opsForZSet().remove(Constants.ORDERS,message);
        }
    }
}
